import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { CustomerMemberIntegralService } from './customer-member-integral.service';
import { DatePipe } from '@angular/common';
import { NzMessageService } from 'ng-zorro-antd/message';
import {PermissionService} from '../../../service/permission.service';

@Component({
  selector: 'app-customer-member-integral',
  templateUrl: './customer-member-integral.component.html',
  styleUrls: ['./customer-member-integral.component.scss'],
  providers: [DatePipe]
})
export class CustomerMemberIntegralComponent implements OnInit {

  // seachForm
  dateArrs: any = []; // 时间段
  seachForms: any = {
    createTime: '', // 开始时间
    endTime: '',  // 结束时间
    source: '',  // 来源-字典获取
    createUser: '', // 操作人
    user: ''  // 用户 ID/姓名/联系方式
  }
  // table
  tableForms: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  // 表格data
  tableData: any = [];

  // 来源下拉list
  sourceLists: any = [];
  // 已选来源
  sourceSelected: any = [];

  // 弹窗
  isVisible: boolean = false;
  // 弹窗form表单
  validateForm!: FormGroup;

  constructor(
    private fb: FormBuilder,
    private datePipe: DatePipe,
    private message: NzMessageService,
    private service: CustomerMemberIntegralService,
    public permission: PermissionService,
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userId: [null, [Validators.required]],
      integralChange: [null, [Validators.required]],
      businessId: [null],
      bak: [null, [Validators.required]]
    });

    // 字典来源
    this.getDictGrowthValue()
    // tabledata
    this.loadData()
  }

  // loadData
  loadData() {
    let params = {
      ...this.seachForms,
      page: this.tableForms.page,
      pageSize: this.tableForms.pageSize
    }

    this.tableData.tableLoading = true;
    this.service.memberIntegralTableData(params).subscribe((res: any) => {
      this.tableData.tableLoading = false;
      const { records, total } = res.data;

      this.tableData = records || [];
      this.tableForms.total = total || 0;
    }, (error: any) => {
      this.tableData.tableLoading = false;
      this.tableForms.total = 0;
    })
  }

  // 获取字典(来源)
  getDictGrowthValue() {
    this.service.dictListData('source_integral').subscribe((res: any) => {
      this.sourceLists = res.data.list || [];
    }, (error: any) => {
      this.sourceLists = [];
    })
  }

  // 搜索
  searchData() {
    this.tableForms.page = 1;
    this.loadData()
  }
  // 重置
  resetData() {
    for (let key in this.seachForms) {
      this.seachForms[key] = '';
    }
    this.dateArrs = [];
    this.sourceSelected = [];

    this.tableForms.page = 1;
    this.loadData()
  }

  // 日期change
  dateChange(result: Date[]) {
    console.log(result);
    this.seachForms.createTime = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd') : '';
    this.seachForms.endTime = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd') : '';
  }

  // 来源change
  sourceChange(event: any) {
    this.seachForms.source = event.length ? event.join(',') : '';
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableForms.page = index;
    this.loadData()
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.tableForms.page = 1;
    this.tableForms.pageSize = sizeNum;

    this.loadData()
  }

  // 手动调节(添加)
  addGrowthItemData() {
    this.service.addIntegralData({...this.validateForm.value}).subscribe((res: any) => {
      this.isVisible = false;
      if (res.code == 0) {
        this.message.success('操作成功');

        this.seachForms.page = 1;
        this.loadData()
      } else {
        this.message.error(res.message || '操作失败');
      }
    }, (error: any) => {
      this.message.error(error || '操作失败');
    })
  }

  // model确定
  handleOk(): void {
    // this.isVisible = false;
    for (const key in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(key)) {
        this.validateForm.controls[key].markAsDirty();
        this.validateForm.controls[key].updateValueAndValidity();
      }
    }
    if (!this.validateForm.valid) {
      return
    }
    for (let key in this.validateForm.value) {
      if (this.validateForm.value[key] == '' || this.validateForm.value[key] == null || this.validateForm.value[key] == undefined) {
        delete this.validateForm.value[key];
      }
    }

    this.addGrowthItemData()
  }
  // model取消
  handleCancel(): void {
    this.isVisible = false;
  }

  // 打开模态框
  openModel(event: any) {
    // console.log('打开model', event);
  }
  // 关闭模态框
  closeModel(event: any) {
    this.validateForm.reset();
  }

  // 来源文字替换
  getSourceText(num: number) {
    let tempObj: any = this.sourceLists.find((item: any) => {
      return item.content == num;
    })
    return tempObj?.name || '-';
  }

  // 输入框输入整数
  formatterDollar = (value: number) => `${value}`;
  parserDollar = (value: string) => value.replace(/^[0-9]*/, '')
}
